﻿using System;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Windows.Forms;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using ContractManager.BLL.Business;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmContracts : XtraFormBase
    {
        #region "Define Variable"
        private readonly BackgroundWorker _loadworker = new BackgroundWorker();
        private int _invId;
        private int _formNo;
        private int _conDetId;
        private string _conDetContent;
        
        private DateTime _currentDate;
        #endregion

        #region "Form Construction"
        public FrmContracts()
        {
            InitializeComponent();
            InitializeControls();
          //  ClsVariable.DoubleBuffer(this);
            _loadworker.DoWork += loadworker_DoWork;
            _loadworker.RunWorkerCompleted += loadworker_RunWorkerCompleted;
            grvContracts.PopupMenuShowing+=GrvContractsOnPopupMenuShowing;
            
        }

        private void GrvContractsOnPopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            if (e.MenuType==GridMenuType.Row)
            {
                popupMenu1.ShowPopup(e.Point);
            }
        }

        #endregion

        #region "Private Method"
        
        private void CheckPer()
        {
            var item = ClsForms.SelectByUserForm(ClsVariable.RoleNo, FormNo);
            if (item == null) return;
            AllowAdd = item.AllowAdd;
            AllowDelete = item.AllowDelete;
            AllowEdit = item.AllowEdit;
            AllowAccess = item.AllowAccess;
            AllowPrint = item.AllowPrint;

            this.LstLockDate = ClsVoucherLock.GetLockByFormNo(FormNo);

        }

        private void LockMenu(bool mnlock)
        {
            bool condition = ClsVariable.IsEditVoucher;
            btnNew.Enabled = AllowAdd;
            btnEdit.Enabled = !mnlock && AllowEdit && condition && LstLockDate.Contains(_currentDate) == false;
            btnDelete.Enabled = !mnlock && AllowDelete && condition && LstLockDate.Contains(_currentDate) == false;
            btnView.Enabled = !mnlock && AllowAccess;
            btnPrint.Enabled = AllowPrint;
        }

        private void InitializeControls()
        {
            grdContracts.DataSource = bdsMain;
            grdContracts.UseEmbeddedNavigator = true;
            grvContracts.OptionsBehavior.Editable = false;
            grvDetail.OptionsBehavior.Editable = false;
        }

        public void GetData()
        {
            if (!_loadworker.IsBusy)
            {
                _loadworker.RunWorkerAsync();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", Text));
            }
        }

        private void DoNew()
        {
            var frm = new FrmContractsDetail
                {
                MasterId = 0,
                AsSysBillStyleId = ClsVariable.AsSysBillStyleId,
                AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                AsPerPersonId = ClsVariable.EmployeeId,
                FormNo = _formNo,

                FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                FormReportLayoutTemplate = FormReportLayoutTemplate,
                FormDetailVatGridLayout = this.FormDetailVatGridLayout,
                VoucherCate = this.VoucherCate,
                IsPrintAfterSave = this.FormIsPrintAfterSave,
                FormAccountDefault = this.FormAccountDefault,
                FormIsNotValidate = this.FormIsNotValidate,
                Text = String.Format("Thông tin {0}", this.Text),
                LstLockDate = this.LstLockDate,
                MdiParent = this.MdiParent,
                WindowState = FormWindowState.Maximized
            };
            frm.Closed += FrmOnClosed;
            frm.Show();
            frm.Focus();
        }

        private void DoEdit()
        {
            _invId = Convert.ToInt32(grvContracts.GetRowCellValue(grvContracts.FocusedRowHandle, FieldNameId));
            var frm = new FrmContractsDetail
                {
                MasterId = _invId,
                AsSysBillStyleId = ClsVariable.AsSysBillStyleId,
                AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                AsPerPersonId = ClsVariable.EmployeeId,
                FormNo = _formNo,
                FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                FormReportLayoutTemplate = FormReportLayoutTemplate,
                FormDetailVatGridLayout = this.FormDetailVatGridLayout,
               
                VoucherCate = this.VoucherCate,
                IsPrintAfterSave = this.FormIsPrintAfterSave,
                FormAccountDefault = this.FormAccountDefault,
                FormIsNotValidate = this.FormIsNotValidate,
                LstLockDate = this.LstLockDate,
                AllowDelete = this.AllowDelete,
                Text = String.Format("Thông tin {0}", this.Text),
                MdiParent = this.MdiParent,
                
                WindowState = FormWindowState.Maximized
            };
            frm.Closed += FrmOnClosed;
            frm.Show();
            frm.Focus();
        }

        private void DoView()
        {
            _invId = Convert.ToInt32(grvContracts.GetRowCellValue(grvContracts.FocusedRowHandle, FieldNameId));

            var frm = new FrmContractsDetail
                {
                MasterId = _invId,
                AsSysBillStyleId = ClsVariable.AsSysBillStyleId,
                AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                AsPerPersonId = ClsVariable.EmployeeId,
                FormNo = _formNo,
                OnlyView = true,

                FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                FormReportLayoutTemplate = FormReportLayoutTemplate,
                FormDetailVatGridLayout = this.FormDetailVatGridLayout,

                VoucherCate = this.VoucherCate,
                IsPrintAfterSave = this.FormIsPrintAfterSave,
                FormAccountDefault = this.FormAccountDefault,
                FormIsNotValidate = this.FormIsNotValidate,
                LstLockDate = this.LstLockDate,
                Text = String.Format("Thông tin {0}", this.Text),
                MdiParent = this.MdiParent,
                
                WindowState = FormWindowState.Maximized
            };
           
            frm.Show();
            frm.Focus();
        }

        private void FrmOnClosed(object sender, EventArgs eventArgs)
        {
            var frmContractsDetail = sender as FrmContractsDetail;
            if (frmContractsDetail != null && frmContractsDetail.SaveClose)
            {
                GetData();
            }
        }

        private void DoDelete()
        {
            _invId = Convert.ToInt32(grvContracts.GetRowCellValue(grvContracts.FocusedRowHandle, FieldNameId));

            string strMasterId = _invId.ToString(CultureInfo.InvariantCulture);
            if (strMasterId.Length== 0) return;
            try
            {
                if (
                        XtraMessageBox.Show(
                                        "Bạn có muốn xoá bản ghi hiện tại không?",
                                        "Thông báo",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == DialogResult.No) return;
                ClsContracts.DeleteByPk(Convert.ToInt32(strMasterId));
                grvContracts.DeleteRow(grvContracts.FocusedRowHandle);
                XtraMessageBox.Show(
                      "Bản ghi đã được xoá. " ,
                      "Thông báo",
                      MessageBoxButtons.OK,
                      MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                       "Có lỗi xảy ra trong quá trình xóa dữ liệu. " + ex.Message,
                       "Thông báo",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
            }
        }

        private void DoPrint()
        {
            grdContracts.ShowPrintPreview();
        }

        private void DoAttachDocument()
        {
            var frm = new FrmContractDetailDocuments
                {
                    ConId = _invId,
                    ConDetId = _conDetId,
                    AsSysBillStyleId = ClsVariable.AsSysBillStyleId,
                    AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                    AsPerPersonId = ClsVariable.EmployeeId,
                    FormNo = _formNo,

                    FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                    FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                    FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                    FormReportLayoutTemplate = FormReportLayoutTemplate,
                    FormDetailVatGridLayout = this.FormDetailVatGridLayout,
                    VoucherCate = this.VoucherCate,
                    IsPrintAfterSave = this.FormIsPrintAfterSave,
                    FormAccountDefault = this.FormAccountDefault,
                    FormIsNotValidate = this.FormIsNotValidate,
                    Text = String.Format("Thông tin hồ sơ đính kèm công việc {0}", _conDetContent),

                    MdiParent = this.MdiParent,
                    WindowState = FormWindowState.Maximized
            };
            frm.Closed += FrmOnClosed;
            frm.Show();
            frm.Focus();
        }

        private void DoPrintDecision()
        {
            const string fileName = "QD_GK";
            string reportName = ClsVariable.GetReportFullPath(fileName);
            var report = new Stimulsoft.Report.StiReport();
            try
            {
                report.Load(reportName);
                ClsVariable.CreateWaitDialog(ClsVariable.StrCaption, "Vui lòng đợi...");
                ClsVariable.SetWaitDialogCaption("Đang nạp dữ liệu báo cáo...");
                DataTable dtReport = ClsReports.DoPrintQdgk(_conDetId);
                report.RegData(dtReport);
                report.Compile();
                ClsVariable.CloseWaitDialog();
                ClsVariable.ApplyReportParam(report, ClsVariable.DtParam);
                report.Render(true);
                report.Show(this.MdiParent);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ClsVariable.CloseWaitDialog();
            }
            
            
        }

        private void DoPrintGnv()
        {
            const string fileName = "QD_GNV";
            string reportName = ClsVariable.GetReportFullPath(fileName);
            var report = new Stimulsoft.Report.StiReport();
            try
            {
                report.Load(reportName);
                ClsVariable.CreateWaitDialog(ClsVariable.StrCaption, "Vui lòng đợi...");
                ClsVariable.SetWaitDialogCaption("Đang nạp dữ liệu báo cáo...");
                DataTable dtReport = ClsReports.DoPrintQdgnv(_conDetId);
                report.RegData(dtReport);
                report.Compile();
                ClsVariable.CloseWaitDialog();
                ClsVariable.ApplyReportParam(report, ClsVariable.DtParam);
                report.Render(true);
                report.Show(this.MdiParent);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ClsVariable.CloseWaitDialog();
            }
            
        }

        #endregion

        #region "Background Worker"

        private void loadworker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var list = ClsContracts.GetAll(this.FormNo,this.VoucherCate,txtPeriod.FromDate,txtPeriod.ToDate);
                e.Result = list;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Loi nap du lieu hop dong: " +ex.Message);
                e.Cancel = true;
            }
        }

        private void loadworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Action a = () =>
            {
                bdsMain.DataSource = (DataTable)e.Result;
            };
            grdContracts.Invoke(a);
            ClsVariable.SetWaitDialogCaption(string.Format("Danh sách {0} đã được nạp", Text));
        }
        #endregion

        #region "Form Event"
        private void FrmContractsLoad(object sender, EventArgs e)
        {
            if (Tag == null) return;
            _formNo = Convert.ToInt32(Tag);
            txtPeriod.Year = ClsVariable.Year;
            txtPeriod.SelectIndex = 25;
            try
            {
                ClsVariable.CreateWaitDialog(ClsVariable.StrCaption, "Vui lòng đợi...");
                ClsVariable.SetWaitDialogCaption("Kiểm tra dữ liệu phân quyền...");
                CheckPer();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", this.Text));
                GetData();
                ClsVariable.CloseWaitDialog();
                FieldNameId = "ConId";
                LockMenu(true);
                grvContracts.FocusedRowHandle = GridControl.AutoFilterRowHandle;
                if (!String.IsNullOrEmpty(FormReportLayoutTemplate))
                {
                    string filePath = ClsVariable.GetRestoreLayoutFullPath(FormReportLayoutTemplate);
                    grvContracts.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
                }
                if (!String.IsNullOrEmpty(FormXtraGridSearchLayout))
                {
                    var filePath = ClsVariable.GetRestoreLayoutFullPath(FormXtraGridSearchLayout);
                    grvDetail.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Có lỗi xảy ra trong quá trình khởi tạo dữ liệu " + ex.Message, "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
            finally
            {
                ClsVariable.CloseWaitDialog();
            }
            
        }

        private void FrmContracts_FormClosing(object sender, FormClosingEventArgs e)
        {
            grdContracts.Dispose();
            grdDetail.Dispose();
        }

        private void FrmContracts_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Dispose();
            this.Close();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnNew":
                    DoNew();
                    break;
                case "btnEdit":
                    DoEdit();
                    break;
                case "btnView"://View Detail Contract
                    DoView();
                    break;
                case "btnDelete":
                    DoDelete();
                    break;
                case "btnRefresh"://Refresh Data
                    GetData();
                    break;
                case "btnPrint"://Print Contract
                    DoPrint();
                    break;
                case "btnAttach"://Attach Document
                    DoAttachDocument();
                    break;
                case "btnPrintDecision":
                    DoPrintDecision();
                    break;
                case "btnPrintQDGNV":
                    DoPrintGnv();
                    break;
                case "btnDesignMasterGrid":
                    ClsVariable.ShowDesignXtraGrid(grdContracts);
                    break;
                case "btnDesignDetailGrid":
                    ClsVariable.ShowDesignXtraGrid(grdDetail);
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            GetData();
        }
        #endregion

        #region "Grid Event"
        private void grvContracts_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0)
            {
                _invId = 0;
                grdDetail.DataSource = null;
                LockMenu(true);
                return;
            }
            if (grvContracts.GetRowCellValue(e.FocusedRowHandle, FieldNameId) == DBNull.Value) return;
            _invId = Convert.ToInt32(grvContracts.GetRowCellValue(e.FocusedRowHandle, FieldNameId));
            _currentDate =
                Convert.ToDateTime(grvContracts.GetRowCellValue(e.FocusedRowHandle, "ConReceiptDate")).Date;
            grdDetail.DataSource = null;
            grdDetail.DataSource = ClsContracts.ListDetail(_invId);
            grvDetail.FocusedRowHandle = GridControl.AutoFilterRowHandle;
            LockMenu(false);
        }

        private void grvDetail_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            _conDetId = e.FocusedRowHandle < 0 ? 0 : Convert.ToInt32(grvDetail.GetRowCellValue(e.FocusedRowHandle, "ConDetId"));
            _conDetContent = e.FocusedRowHandle < 0 ? "" : String.Format("{0}", grvDetail.GetRowCellValue(e.FocusedRowHandle, "ConDetContent"));

            btnAttach.Enabled = _invId>0 || _conDetId > 0;
        }

        #endregion

       

        

        

        

    }
}
